package com.ysx.teacher.day20210923.ch08.dao.impl;

import com.ysx.teacher.day20210923.ch08.dao.StudentDao;
import com.ysx.teacher.day20210923.ch08.entity.StudentEntity;
import com.ysx.teacher.day20210923.ch08.utils.DBUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class StudentDaoImpl implements StudentDao {

    @Override
    public int addStudent(StudentEntity student) throws  Exception{
        // 1 获取mysql连接
        Connection conn= DBUtil.getConnection();
        System.out.println(conn);

        // 2 拼写好sql语句 代码自动生成工作 单表的CRUD全部一次性给你写好
        String sql="insert into crm_student_t values(?,?,?)";

        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,student.getId());
        ps.setString(2,student.getStudentName());
        ps.setInt(3,student.getStudentAge());

        int i = ps.executeUpdate();
        System.out.println(i);
        return  i;


        // 3 调用api把student保存到数据库中
    }

    @Override
    public StudentEntity findStudentById(int id) throws  Exception {

        StudentEntity stu=new StudentEntity();
        // 1 获取mysql连接
        Connection conn= DBUtil.getConnection();

        System.out.println(conn);
        // 2 拼写好sql语句 代码自动生成工作 单表的CRUD全部一次性给你写好
        String sql="select ID as id,STUDENT_NAME as studentName,STUDENT_AGE as studentAge from crm_student_t where id=?";

        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,id);

        ResultSet rs = ps.executeQuery();

        if(rs.next()){
            int idd = rs.getInt(1);
            System.out.println(idd);
            String name =rs.getString(2);
            int age =rs.getInt(3);
            stu.setId(idd);
            stu.setStudentName(name);
            stu.setStudentAge(age);
        }


        return  stu;
    }
}
